﻿import { Component, Injector, ViewChild} from '@angular/core';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { AppComponentBase } from '@shared/common/app-component-base';
import * as _ from 'lodash';
import { finalize } from 'rxjs/operators';
import { Tab } from './tab.model';
import { Paginator } from 'primeng/components/paginator/paginator';
import { Table } from 'primeng/components/table/table';
import { LazyLoadEvent } from 'primeng/components/common/lazyloadevent';
import { CreateOrEditRequirementPackageModalComponent } from './create-or-edit-requirement-package-modal.component'
import { RequirementPackageDto,RequirementPackageServiceProxy,RequirementPackageState } from '@shared/service-proxies/service-proxies';
import { RequirementTabComponent } from './requirement_tab.component';
import { AbpSessionService } from '@abp/session/abp-session.service';

@Component({
    templateUrl: './requirement.component.html',
    styleUrls: ['./requirement.component.less'],
    animations: [appModuleAnimation()]
})
export class RequirementComponent extends AppComponentBase{
    @ViewChild('createOrEditRequirementPackageModal') createOrEditRequirementPackageModal: CreateOrEditRequirementPackageModalComponent;
    @ViewChild('requirementTabComponent') requirementTabComponent: RequirementTabComponent;
    @ViewChild('dataTable') dataTable: Table;
    @ViewChild('paginator') paginator: Paginator;
    tabs: Array<Tab>;
    tabObject:{
        filterText:""
    };
    loading = false;
    caches: any = null;
    logs: any = '';
    filterText = '';
    hidden = true;
    selectAll:boolean=true;

    constructor(
        injector: Injector,
        private _requirementPackageService: RequirementPackageServiceProxy,
        private _abpSessionService :AbpSessionService) {
        super(injector);
        this.tabs = new Array<Tab>();
    }
    addTab(requirementPackageDto: RequirementPackageDto): void {
        if (this.tabs.length == 0) {
            let tab: Tab = new Tab("需求详细管理【" + requirementPackageDto.displayName + "】");
            tab.index = this.tabs.length;
            tab.requirementPackageId = requirementPackageDto.id;
            tab.record = requirementPackageDto;
            tab.active = true;
            this.tabs.push(tab);
        } else {
            this.tabs[0].active = true;
            this.tabs[0].name = "需求详细管理【" + requirementPackageDto.displayName + "】";
            this.tabs[0].requirementPackageId = requirementPackageDto.id;
        }
        // requirementTabComponent创建是延时的，第一次打开不存在
        if (this.requirementTabComponent) {
            this.requirementTabComponent.setRequirementPackage(requirementPackageDto);
            this.requirementTabComponent.getRequirementItems();
        }
    }
    clearTab(): void {

    }
    createRequirementItem(tab:Tab,event?: LazyLoadEvent):void{
        
    }
    createOrEditRequirementPackage(requirementPackage: RequirementPackageDto): void {
        this.createOrEditRequirementPackageModal.show(requirementPackage);
    }
    deleteRequirementPackage(requirementPackageDto :RequirementPackageDto): void {
        this.message.confirm(
            '需求包将被删除',
            this.l('AreYouSure'),
            (isConfirmed) => {
                if (isConfirmed) {
                    this._requirementPackageService.deletePackage(requirementPackageDto.id)
                    .pipe(finalize(() => { this.getRequirementPackages();}))
                    .subscribe(() => {
                        this.notify.info(this.l('DeletedSuccessfully'));
                    });
                }
            }
        );
    }
    getRequirementPackages(event?: LazyLoadEvent) {
        if (this.primengTableHelper.shouldResetPaging(event)) {
            this.paginator.changePage(0);
            return;
        }
        this.primengTableHelper.showLoadingIndicator();
        if(this.selectAll){
            this._requirementPackageService.getAllPackages(
                this.filterText,
                this.primengTableHelper.getSorting(this.dataTable),
                this.primengTableHelper.getMaxResultCount(this.paginator, event),
                this.primengTableHelper.getSkipCount(this.paginator, event))
                .pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator())).subscribe(result => {
                    this.primengTableHelper.totalRecordsCount = result.totalCount;
                    this.primengTableHelper.records = result.items;
                    this.primengTableHelper.hideLoadingIndicator();
                });
        }else{
            let userId:string = this._abpSessionService.userId.toString();
            this._requirementPackageService.getAllPackagesByUser(
                userId,
                this.filterText,
                this.primengTableHelper.getSorting(this.dataTable),
                this.primengTableHelper.getMaxResultCount(this.paginator, event),
                this.primengTableHelper.getSkipCount(this.paginator, event))
                .pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator())).subscribe(result => {
                    this.primengTableHelper.totalRecordsCount = result.totalCount;
                    this.primengTableHelper.records = result.items;
                    this.primengTableHelper.hideLoadingIndicator();
                });
        }


    }
    /**
     * 需求包提交审核
     * @param record 
     */
    applyPackage(record: RequirementPackageDto) {
        this.message.confirm(
            '提交需求包审核？',
            this.l('AreYouSure'),
            (isConfirmed) => {
                if (isConfirmed) {
                    this.primengTableHelper.showLoadingIndicator();
                    this._requirementPackageService.applyPackage(record.id)
                        .pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator())).subscribe(result => {
                            this.primengTableHelper.hideLoadingIndicator();
                            this.getRequirementPackages();
                        });
                }
            }
        );
    }
    /**
     * 需求包审核撤销
     * @param record 
     */
    cancelApplyPackage(record: RequirementPackageDto) {
        this.message.confirm(
            '撤销需求包审核？',
            this.l('AreYouSure'),
            (isConfirmed) => {
                if (isConfirmed) {
                    this.primengTableHelper.showLoadingIndicator();
                    this._requirementPackageService.cancelApplyPackage(record.id)
                        .pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator())).subscribe(result => {
                            this.primengTableHelper.hideLoadingIndicator();
                            this.getRequirementPackages();
                        });
                }
            }
        );
    }
    /**
     * 需求包审核同意
     * @param record 
     */
    agreePackage(record: RequirementPackageDto) {
        this.message.confirm(
            '同意该需求包？',
            this.l('AreYouSure'),
            (isConfirmed) => {
                if (isConfirmed) {
                    this.primengTableHelper.showLoadingIndicator();
                    this._requirementPackageService.agreePackage(record.id)
                        .pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator())).subscribe(result => {
                            this.primengTableHelper.hideLoadingIndicator();
                            this.getRequirementPackages();
                        });
                }
            }
        );
    }
    getRequirementPackageStateString(state:number):string{
        return RequirementPackageState[state];
    }



    downloadWebLogs = function () {
        const self = this;
        self._webLogService.downloadWebLogs().subscribe((result) => {
            self._fileDownloadService.downloadTempFile(result);
        });
    };


    onResize(event): void {
        
    }

    ngOnInit(): void {
        const self = this;
    }
}
